package com.yunao.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yunao.commons.Exception.YunaoException;
import com.yunao.commons.enums.NeedReportEnum;
import com.yunao.commons.enums.ResultEnum;
import com.yunao.commons.utils.ResultVOUtil;
import com.yunao.commons.vo.ResultVO;
import com.yunao.entity.AloneReport;
import com.yunao.entity.User;
import com.yunao.service.AlonereportService;
import com.yunao.service.ReportService;
import com.yunao.service.UserService;
import com.yunao.service.report.Convert;
import com.yunao.service.report.DateUtil;
import com.yunao.service.report.StringUtil;
import com.yunao.service.report.esou.*;
import com.yunao.web.annotation.UserLoginToken;
import com.yunao.web.form.AloneReportForm;
import com.yunao.web.utils.TokenUtil;
import com.zhongsou.search.core.query.txtexpr.TxtExprVerify;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 报告专题
 *
 * @author wuyc
 */
@RestController
@Scope("prototype")
@UserLoginToken
@RequestMapping("/search/aloneReport")
@Slf4j
public class AloneReportAction {

    @Autowired
    private AlonereportService aloneReportService;


    @Autowired
    private ReportService reportService;


    @Autowired
    UserService userService;

    @RequestMapping("/list")
    @UserLoginToken
    public ResultVO list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pagesize,
            HttpServletRequest request
    ) {
        String userId = TokenUtil.getTokenUserId();
        Pageable pageable = PageRequest.of(page - 1, pagesize, new Sort(Sort.Direction.DESC, "id"));
        List<AloneReport> aloneReports = aloneReportService.findAllByUserId(Convert.getInt(userId), pageable);
        return ResultVOUtil.success(aloneReports);
    }

    @RequestMapping("/add")
    @UserLoginToken
    @Transactional
    public ResultVO add(@Valid AloneReportForm reportForm,
                        BindingResult bindingResult,
                        HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            log.error("【创建报告】参数不正确");
            throw new YunaoException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        User userOutput = TokenUtil.getTokenUser(userService);
        String[] locations = null;
        String[] mediaTypes = null;
        String[] emotions = null;
        String[] manners = null;
        String manner = reportForm.getManner();
        String location = Optional.ofNullable(reportForm.getLocation()).orElse("");
        String mediaType = Optional.ofNullable(reportForm.getMediaType()).orElse("");
        String emotion = Optional.ofNullable(reportForm.getEmotion()).orElse("");
        if (location.contains(",")) {
            locations = location.split(",");
        } else {
            locations = new String[]{location};
        }
        if (mediaType.contains(",")) {
            mediaTypes = mediaType.split(",");
        } else {
            mediaTypes = new String[]{mediaType};
        }
        if (emotion.contains(",")) {
            emotions = emotion.split(",");
        } else {
            emotions = new String[]{emotion};
        }
        if (manner.contains(",")) {
            manners = manner.split(",");
        } else {
            manners = new String[]{manner};
        }

        ResultVO<String> error = checkFormat(reportForm.getName(), reportForm.getKeyword(), reportForm.getRemword(), locations, mediaTypes, emotions, reportForm.getTitle(),
                reportForm.getAuthor(), reportForm.getWebattr(), manners, reportForm.getAddr(), userOutput.getUserId(), userOutput.getOrganId() + "");
        if (error != null) {
            return error;
        }
        return ResultVOUtil.success();
    }

    /**
     * showdoc
     *
     * @param aid 必选 int 报告专题ID
     * @return {code: 0,msg: "成功",data:""}
     * @catalog API文档/报告模块
     * @title 停止自动报告
     * @description 关闭自动报告
     * @method get
     * @url /report/aloneReport/stop
     * @remark
     * @number 08
     */
    @UserLoginToken
    @RequestMapping("/stop")
    public ResultVO<String> stop(
            Integer aid
    ) {
        AloneReport aloneReport = aloneReportService.findById(aid);
        aloneReport.setNeedReport(NeedReportEnum.NON_REPORT.getCode()+"");
        aloneReportService.updateOne(aloneReport);
        return ResultVOUtil.success();
    }

    /**
     * showdoc
     *
     * @param aid 必选 int 报告专题ID
     * @return {code: 0,msg: "成功",data: ""}
     * @catalog API文档/报告模块
     * @title 开启自动报告
     * @description
     * @method get
     * @url /report/aloneReport/open
     * @remark
     * @number 09
     */
    @UserLoginToken
    @RequestMapping("/open")
    public ResultVO<String> open(
            Integer aid
    ) {

        AloneReport aloneReport = aloneReportService.findById(aid);
        aloneReport.setNeedReport(NeedReportEnum.NEED_REPORT.getCode()+"");
        aloneReportService.updateOne(aloneReport);
        return ResultVOUtil.success();
    }

    /**
     * showdoc
     *
     * @param aid 必选 int 报告专题ID
     * @return {code: 0,msg: "成功",data:""}
     * @catalog API文档/报告模块
     * @title 删除自动报告
     * @description
     * @method post
     * @url /report/aloneReport/delete
     * @remark
     * @number 10
     */
    @UserLoginToken
    @RequestMapping(value = "/delete", method = {RequestMethod.POST})
    public ResultVO<String> delete(
            Integer aid
    ) throws Exception {
        aloneReportService.delete(aid);
        return ResultVOUtil.success();
    }

    /**
     * showdoc
     *
     * @param aids 必选 string 报告专题ID数组
     * @return {code: 0,msg: "成功",data:""}
     * @catalog API文档/报告模块
     * @title 批量删除自动报告
     * @description
     * @method post
     * @url /report/aloneReport/deleteSubs
     * @remark aids由字符串拼接，例如 23,45,12
     * @number 11
     */
    @UserLoginToken
    @RequestMapping(value = "/deleteSubs", method = {RequestMethod.POST})
    public ResultVO<String> deleteSubs(
            String aids
    ) {
        String[] aidArray = aids.split(",");
        if (aids != null) {
            for (String aid : aidArray) {
                aloneReportService.delete(Integer.parseInt(aid));
            }
        }
        return ResultVOUtil.success();
    }

    /**
     * showdoc
     *
     * @param aid 必选 int 报告专题ID
     * @return {code: 0,msg: "成功",data: {}}
     * @catalog API文档/报告模块
     * @title 获取单个报告
     * @description 修改自动报告之前的查询
     * @method post
     * @url /report/aloneReport/findOne
     * @remark
     * @number 12
     */
    @UserLoginToken
    @RequestMapping(value = "/findOne", method = {RequestMethod.POST})
    public ResultVO<String> editUI(
            Integer aid
    ) throws Exception {
        AloneReport aloneReport = aloneReportService.findById(aid);
        return ResultVOUtil.success(aloneReport);
    }

    @PostMapping("/edit")
    @Transactional
    @UserLoginToken
    public ResultVO<String> edit(@Valid AloneReportForm reportForm,
                                 HttpServletRequest request
    ) throws Exception {
        User userOutput = TokenUtil.getTokenUser(userService);
        if (StringUtils.isEmpty(reportForm.getAid())) {
            return ResultVOUtil.error(102, "请选择有效的报告");
        }
        AloneReport aloneReport = aloneReportService.findById(Convert.getInt(reportForm.getAid()));
        ResultVO<String> error = checkFormatAndUpdate(reportForm, userOutput, aloneReport);
        if (error != null) {
            return error;
        }
        return ResultVOUtil.success();
    }

    /*
     * showdoc
     * @catalog API文档/报告模块
     * @title  浏览报告
     * @description 创建自动报告界面的预浏览报告功能
     * @method post
     * @url /report/aloneReport/preview
     * @param name 必选 int 报告名称
     * @param keyword 必选 int 关键词
     * @param remword 可选 int 排除词
     * @param location 可选 int 监测地点
     * @param mediaType 可选 int 监测类型
     * @param emotion 可选 int 情感类型
     * @param title 可选 int 标题
     * @param author 可选 int 作者
     * @param webattr 可选 int 网站
     * @param manner 必选 int 报告类型
     * @param addr 必选 int 发送人邮箱
     * @return {code: 0,msg: "成功",data: {}}
     * @remark
     * @number 14
     */
    @UserLoginToken
    @RequestMapping(value = "/preview", method = {RequestMethod.POST})
    public ResultVO<String> previewReport(
            String name,
            String keyword,
            String remword,
            String location,
            String mediaType,
            String emotion,
            String title,
            String author,
            String webattr,
            String manner,
            String addr,
            HttpServletRequest request
    ) throws IOException {
        User userOutput = TokenUtil.getTokenUser(userService);
        String[] locations = null;
        String[] mediaTypes = null;
        String[] emotions = null;
        String[] manners = null;
        if (location.contains(",")) {
            locations = location.split(",");
        } else {
            locations = new String[]{location};
        }
        if (mediaType.contains(",")) {
            mediaTypes = mediaType.split(",");
        } else {
            mediaTypes = new String[]{mediaType};
        }
        if (emotion.contains(",")) {
            emotions = emotion.split(",");
        } else {
            emotions = new String[]{emotion};
        }
        if (manner.contains(",")) {
            manners = manner.split(",");
        } else {
            manners = new String[]{manner};
        }


        // 专题名称不为空
        if (name == null || name.length() == 0) {
            return ResultVOUtil.error(ResultEnum.REPORT_NAME_ERROR);
        }
        if (name.length() < 2) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_NAMESHORT_ERROR);
        }
        if (name.length() > 15) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_NAMELONG_ERROR);
        }
        char[] charw = keyword.toCharArray();
        for (int i = 0; i < charw.length; i++) {
            System.out.println(isChinesePunctuation(charw[i]));
            if (isChinesePunctuation(charw[i])) {
                return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_ERROR);
            }
        }
        if (keyword == null || keyword.length() == 0) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_NULL_ERROR);
        }
        if (remword.contains(",")) {
            remword = remword.replaceAll(" +", ",");
            String[] remwords = remword.split(",");
            for (int i = 0; i < remwords.length; i++) {
                if (keyword.equals(remwords[i])) {
                    return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_AND_RWORD_ERROR);
                }
                for (int j = remwords.length - 1; j > i; j--) {
                    if (remwords[i].equals(remwords[j])) {
                        return ResultVOUtil.error(ResultEnum.ALONEREPORT_REMWORD_REPEAT_ERROR);
                    }
                }
            }
        }
        if (keyword.equals(remword)) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_AND_RWORD_ERROR);
        }
        // 验证关键词
        try {
            TxtExprVerify verity = new TxtExprVerify(keyword);
            if (!verity.isPassed()) {
                return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_MAY_ERROR);
            }
        } catch (Exception e) {

        }
        if (remword == null || remword.length() == 0) {
            remword = "";
        }
        remword = remword.replace(",", "");
        System.out.println(remword);
        if (remword.contains("-")) {
            remword = remword.replace("-", " ");
        }
        remword = remword.trim();
        remword = remword.replace(" ", "|");
        System.out.println(remword);
        AloneReport aloneReport = new AloneReport();
        String[] province = locations;
        String p = "";

        if (province != null) {
            aloneReport.setLocal(p);
        }
        aloneReport.setName(name); // 专题名称
        aloneReport.setRemword(remword);
        System.out.println(keyword);
        System.out.println(remword);
        if (!remword.contains("|")) {
            aloneReport.setWord(keyword + "-" + remword);
        }
        if (remword.contains("|")) {
            aloneReport.setWord(keyword + "-(" + remword + ")"); // 关键词
        }
        System.out.println(aloneReport.getWord());
        if (remword == null || remword.length() == 0)
            aloneReport.setWord(keyword);

        String[] mediatype = mediaTypes;
        String m = "";

        if (mediatype != null) {
            for (int i = 0; i < mediatype.length; i++) {
                if (i == mediatype.length - 1) {
                    m += mediatype[i];
                } else {
                    m += mediatype[i] + ",";
                }
                aloneReport.setMediatype(m);

            }

        }
        String e = "";
        if (emotions != null) {
            for (int i = 0; i < emotions.length; i++) {
                if (i == emotions.length - 1) {
                    e += emotions[i];
                } else {
                    e += emotions[i] + ",";
                }
                aloneReport.setEmotion(e);

            }

        }
        aloneReport.setTitle(title);
        String webAttrs = webattr.trim();
        String[] webAttr = webAttrs.split(",");
        if (webAttr.length > 5) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_WEBATTR_ERROR);
        }
        for (int i = 0; i < webAttr.length; i++) {
            for (int j = webAttr.length - 1; j > i; j--) {
                if (webAttr[i].equals(webAttr[j])) {
                    return ResultVOUtil.error(ResultEnum.ALONEREPORT_WEBATTR_REPEAT_ERROR);
                }
            }
        }
        for (int i = 0; i < webAttr.length; i++) {
            if (webAttr[i] == null || webAttr[i].equals(""))
                webAttr[i] = "";
            else if (!isUrl(webAttr[i])) {
                return ResultVOUtil.error(ResultEnum.ALONEREPORT_WEBATTR_FORMAT_ERROR);
            }
        }
        String query = null;
        try {
            query = this.getQuery(
                    webAttrs,
                    title,
                    author
            );
        } catch (UnsupportedEncodingException e1) {
            log.error(e1.getMessage());
        }
        aloneReport.setWebattr(webattr);
        aloneReport.setAuthor(author);
        aloneReport.setQuery(query); // 查询条件
        aloneReport.setUserId(userOutput.getUserId()); // 所属用户
        aloneReport.setSubjectOrganizationId(userOutput.getOrganId() + ""); // 所属组织

        int reportManner = StringUtil.getReportManner(manners);
        if (reportManner > 7 || reportManner < 1) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_MANNER_ERROR);
        }
        aloneReport.setNeedReport("1");
        aloneReport.setReportmanner(reportManner + "");
        SimpleDateFormat timeFormat = new SimpleDateFormat(DateUtil.TIME_FORMAT);
        aloneReport.setCreatetime(timeFormat.format(new Date())); // 时间条件

        String path = run(aloneReport);
        JSONObject data = new JSONObject();
        data.put("path", path);
        return ResultVOUtil.success(data);
    }

    /**
     * showdoc
     *
     * @param aid 必选 int 报告专题ID
     * @return {code: 0,msg: "成功",data:{}}
     * @catalog API文档/报告模块
     * @title 在线生成舆情报告
     * @description 发送报告按钮
     * @method post
     * @url /report/aloneReport/currentreport
     * @remark
     * @number 15
     */
    @UserLoginToken
    @RequestMapping(value = "/currentreport", method = {RequestMethod.POST})
    public ResultVO currentreport(
            Integer aid
    ) throws IOException {

        AloneReport ap = aloneReportService.findById(aid);
        if (ap.getReportaddrs() == null) {
//            return ResultVOUtil.error(ResultEnum.ALONEREPORT_ADDR_ERROR);
            return ResultVOUtil.error(ResultEnum.PARAM_ERROR);
        }
        try {
            log.info(ap.getReportaddrs());
            ReportTask2 rt = new ReportTask2(aloneReportService, reportService);
            rt.currentreport(aid);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultVOUtil.error(53, "发送失败");
        }

        return ResultVOUtil.success();
    }

    /**
     * 生成舆情报告
     *
     * @param aloneReport 报告实体
     */
    private String run(AloneReport aloneReport) {
        System.out.println("running..a");
        int i = 0;
        System.out.println("start...");
        String docPath = "";
        System.out.println("----reproting----" + i++);

        // 自动报告方式
        String manner = aloneReport.getReportmanner();
        aloneReport.setId(0);
        // 日报
        if (manner.equals("1") || manner.equals("3") || manner.equals("5") || manner.equals("7")) {
            ReportDaily2 daily = new ReportDaily2(aloneReport, reportService);
            try {
                log.info("【" + aloneReport.getName() + "】日报开始发送");
                docPath += daily.createMailc() + ",";
                log.info("【" + aloneReport.getName() + "】日报发送完成");
            } catch (Exception e) {
                e.printStackTrace();
                log.info("【" + aloneReport.getName() + "】日报发送异常");
            }
        }
        // 周报
        if (manner.equals("2") || manner.equals("3") || manner.equals("6") || manner.equals("7")) {
            ReportWeekly2 weekly = new ReportWeekly2(aloneReport, reportService);
            try {
                log.info("【" + aloneReport.getName() + "】周报开始发送");
                docPath += weekly.createMailc() + ",";
                log.info("【" + aloneReport.getName() + "】周报发送完成");
            } catch (Exception e) {
                e.printStackTrace();
                log.info("【" + aloneReport.getName() + "】周报发送异常");
            }
        }
        // 月报
        if (manner.equals("4") || manner.equals("5") || manner.equals("6") || manner.equals("7")) {
            ReportMonthly2 monthly = new ReportMonthly2(aloneReport, reportService);
            try {
                log.info("【" + aloneReport.getName() + "】月报开始发送");
                docPath += monthly.createMailc();
                log.info("【" + aloneReport.getName() + "】月报发送完成");
            } catch (Exception e) {
                e.printStackTrace();
                log.info("【" + aloneReport.getName() + "】月报发送异常");
            }
        }
        return docPath;
    }

    private ResultVO<String> checkFormat(
            String name,
            String keyword,
            String remword,
            String[] location,
            String[] mediaType,
            String[] emotion,
            String title,
            String author,
            String webattr,
            String[] manner,
            String addr,
            Integer userid,
            String organizationId) {
        // 用户专题名唯一
        int count = Integer.parseInt(aloneReportService.countByUserIdAndName(userid, name));
        if (count > 0) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_NAME_ERROR);
        }
        char[] charw = keyword.toCharArray();
        for (int i = 0; i < charw.length; i++) {
            System.out.println(isChinesePunctuation(charw[i]));
            if (isChinesePunctuation(charw[i])) {
                return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_ERROR);
            }
        }
        if (stringFilter(keyword)) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORDCHAR_ERROR);
        }
        AloneReport aloneReport = new AloneReport();
        remword = Optional.ofNullable(remword).orElse("");
        if (remword.contains("-")) {
            remword = remword.replace("-", ",");
        }
        remword = remword.trim();
        remword = remword.replace(",", "|");
        if (stringFilter(remword)) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORDCHAR_ERROR);
        }
        if (remword.contains(",")) {
            remword = remword.replaceAll(" +", ",");
            String[] remwords = remword.split(",");
            for (int i = 0; i < remwords.length; i++) {
                if (keyword.equals(remwords[i])) {
                    return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_AND_RWORD_ERROR);
                }
                for (int j = remwords.length - 1; j > i; j--) {
                    if (remwords[i].equals(remwords[j])) {
                        return ResultVOUtil.error(ResultEnum.ALONEREPORT_REMWORD_REPEAT_ERROR);
                    }
                }
            }
        }
        if (keyword.equals(remword)) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_AND_RWORD_ERROR);
        }
        if (!remword.contains("|")) {
            aloneReport.setWord(keyword + "-" + remword);
        }
        if (remword.contains("|")) {
            aloneReport.setWord(keyword + "-(" + remword + ")"); // 关键词
        }
        if (keyword.contains("-")) {
            String[] words = keyword.split("-", 2);
            remword += "," + words[1];
            keyword = words[0];
        }
        // 验证关键词
        try {
            TxtExprVerify verity = new TxtExprVerify(keyword);
            if (!verity.isPassed()) {
                return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_MAY_ERROR);
            }
        } catch (Exception e) {

        }
        String[] province = location;
        String p = "";
        if (province != null) {
            for (int i = 0; i < province.length; i++) {
                if (i == province.length - 1) {
                    p += province[i];
                } else {
                    p += province[i] + ",";
                }
                aloneReport.setLocal(p);
            }
        }
        aloneReport.setName(name); // 专题名称
        aloneReport.setRemword(remword);
        System.out.println(keyword);
        System.out.println(remword);
        System.out.println(aloneReport.getWord());
        aloneReport.setWord(keyword);
        String[] mediatype = mediaType;
        String m = "";
        for (int i = 0; i < mediatype.length; i++) {
            if (i == mediatype.length - 1) {
                m += mediatype[i];
            } else {
                m += mediatype[i] + ",";
            }
            aloneReport.setMediatype(m);
        }
        String e = "";
        for (int i = 0; i < emotion.length; i++) {
            if (i == emotion.length - 1) {
                e += emotion[i];
            } else {
                e += emotion[i] + ",";
            }
            aloneReport.setEmotion(e);
        }
        aloneReport.setTitle(title);
        webattr = Optional.ofNullable(webattr).orElse("");
        String webAttrs = "";
        if (!StringUtils.isEmpty(webattr)) {
            webAttrs = webattr.trim();
            String[] webAttr = webAttrs.split(",");
            if (webAttr.length > 5) {
                return ResultVOUtil.error(ResultEnum.ALONEREPORT_WEBATTR_ERROR);
            }
            for (int i = 0; i < webAttr.length; i++) {
                for (int j = webAttr.length - 1; j > i; j--) {
                    if (webAttr[i].equals(webAttr[j])) {
                        return ResultVOUtil.error(ResultEnum.ALONEREPORT_WEBATTR_REPEAT_ERROR);
                    }
                }
            }
            for (int i = 0; i < webAttr.length; i++) {
                if (webAttr[i] == null || webAttr[i].equals(""))
                    webAttr[i] = "";
                else if (!isUrl(webAttr[i])) {
                    return ResultVOUtil.error(ResultEnum.ALONEREPORT_WEBATTR_FORMAT_ERROR);
                }
            }
        }
        title = Optional.ofNullable(title).orElse("");
        author = Optional.ofNullable(author).orElse("");
        String query = null;
        try {
            query = this.getQuery(
                    webAttrs,
                    title,
                    author
            );
        } catch (UnsupportedEncodingException e1) {
            log.error(e1.getMessage());
        }
        aloneReport.setWebattr(webattr);
        aloneReport.setAuthor(author);
        aloneReport.setQuery(query); // 查询条件
        aloneReport.setUserId(userid); // 所属用户
        aloneReport.setSubjectOrganizationId(organizationId); // 所属组织
        /*
         * 报告地址
         */
        String[] addrs = Convert.split(addr, ",");
        String Useraddrs = "";
        Pattern email = Pattern.compile(StringUtil.VALIDATE_EMAIL);
        Pattern mobile = Pattern.compile(StringUtil.VALIDATE_MOBILE);
        if (addrs.length > 1) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_WEBATTR_ONE_ERROR);
        }
        for (String add : addrs) {
            if (!email.matcher(add).matches() && !mobile.matcher(add).matches()) {
                return ResultVOUtil.error(55, "添加失败，报告发送地址：" + addr + " 错误！");
            }
            Useraddrs = addr;
        }
        if (Useraddrs == "") {
            return ResultVOUtil.error(ResultEnum.REPORT_EMAIL_ERROR);
        }

        int reportManner = StringUtil.getReportManner(manner);
        if (reportManner > 7 || reportManner < 1) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_MANNER_ERROR);
        }
        aloneReport.setNeedReport("1");
        aloneReport.setReportmanner(reportManner + "");
        aloneReport.setReportaddrs(Useraddrs);
        SimpleDateFormat timeFormat = new SimpleDateFormat(DateUtil.TIME_FORMAT);
        aloneReport.setCreatetime(timeFormat.format(new Date())); // 时间条件
        // 保存关键词
        aloneReportService.insertAloneReport(aloneReport);
        return null;
    }

    private ResultVO<String> checkFormatAndUpdate(AloneReportForm reportForm,
                                                  User user,
                                                  AloneReport aloneReport
    ) {
        // 用户专题名唯一
        int count = Integer.parseInt(aloneReportService.countByUserIdAndName(user.getUserId(), reportForm.getName()));
        if (!(aloneReport.getName().equals(reportForm.getName()))) {
            if (count > 0) {
                return ResultVOUtil.error(ResultEnum.ALONEREPORT_NAME_ERROR);
            }
        }
        String[] locations = null;
        String[] mediaTypes = null;
        String[] emotions = null;
        String[] manners = null;
        String location = Optional.ofNullable(reportForm.getLocation()).orElse("");
        String mediaType = Optional.ofNullable(reportForm.getMediaType()).orElse("");
        String emotion = Optional.ofNullable(reportForm.getEmotion()).orElse("");
        String manner = reportForm.getManner();
        if (location.contains(",")) {
            locations = location.split(",");
        } else {
            locations = new String[]{location};
        }
        if (mediaType.contains(",")) {
            mediaTypes = mediaType.split(",");
        } else {
            mediaTypes = new String[]{mediaType};
        }
        if (emotion.contains(",")) {
            emotions = emotion.split(",");
        } else {
            emotions = new String[]{emotion};
        }
        if (manner.contains(",")) {
            manners = manner.split(",");
        } else {
            manners = new String[]{manner};
        }
        String remword = Optional.ofNullable(reportForm.getRemword()).orElse("");
        String keyword = reportForm.getKeyword();
        char[] charw = keyword.toCharArray();
        for (int i = 0; i < charw.length; i++) {
            System.out.println(isChinesePunctuation(charw[i]));
            if (isChinesePunctuation(charw[i])) {
                return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_ERROR);
            }
        }
        if (stringFilter(keyword)) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORDCHAR_ERROR);
        }
        if (StringUtils.isNotEmpty(remword) && stringFilter(remword)) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORDCHAR_ERROR);
        }
        if (keyword.contains("-")) {
            String[] words = keyword.split("-", 2);
            remword += "," + words[1];
            keyword = words[0];
        }
        if (keyword == null || keyword.length() == 0) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_NULL_ERROR);
        }
        if (remword.contains(",")) {
            remword = remword.replaceAll(" +", ",");
            String[] remwords = remword.split(",");
            for (int i = 0; i < remwords.length; i++) {
                if (keyword.equals(remwords[i])) {
                    return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_AND_RWORD_ERROR);
                }
                for (int j = remwords.length - 1; j > i; j--) {
                    if (remwords[i].equals(remwords[j])) {
                        return ResultVOUtil.error(ResultEnum.ALONEREPORT_REMWORD_REPEAT_ERROR);
                    }
                }
            }
        }
        if (keyword.equals(remword)) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_AND_RWORD_ERROR);
        }
        // 验证关键词
        try {
            TxtExprVerify verity = new TxtExprVerify(keyword);
            if (!verity.isPassed()) {
                return ResultVOUtil.error(ResultEnum.ALONEREPORT_KEYWORD_MAY_ERROR);
            }
        } catch (Exception e) {

        }
        if (remword.contains("-")) {
            remword = remword.replace("-", ",");
        }
        remword = remword.trim();
        remword = remword.replace(",", "|");
        System.out.println("remword:" + remword);
        String[] province = locations;
        String p = "";
        if (province != null) {
            for (int i = 0; i < province.length; i++) {

                if (i == province.length - 1) {
                    p += province[i];
                } else {
                    p += province[i] + ",";
                }
                aloneReport.setLocal(p);
            }

        }
        aloneReport.setName(reportForm.getName()); // 专题名称
        aloneReport.setRemword(remword);
        System.out.println(keyword);
        System.out.println(remword);
        if (StringUtils.isEmpty(remword)){
            aloneReport.setWord(keyword);
        }else {
            if (!remword.contains("|")) {
                aloneReport.setWord(keyword + "-" + remword);
            }
            if (remword.contains("|")) {
                aloneReport.setWord(keyword + "-(" + remword + ")"); // 关键词
            }
        }
        System.out.println("报告关键词" + aloneReport.getWord());
        if (StringUtils.isNotEmpty(remword))
            aloneReport.setWord(keyword);
        String[] mediatype = mediaTypes;
        String m = "";

        if (mediatype != null) {
            for (int i = 0; i < mediatype.length; i++) {
                if (i == mediatype.length - 1) {
                    m += mediatype[i];
                } else {
                    m += mediatype[i] + ",";
                }
                aloneReport.setMediatype(m);
            }
        }
        String e = "";
        if (emotions != null) {
            for (int i = 0; i < emotions.length; i++) {
                if (i == emotions.length - 1) {
                    e += emotions[i];
                } else {
                    e += emotions[i] + ",";
                }
                aloneReport.setEmotion(e);
            }
        }
        String title = Optional.ofNullable(reportForm.getTitle()).orElse("");
        String author = Optional.ofNullable(reportForm.getAuthor()).orElse("");
        String webattr = Optional.ofNullable(reportForm.getWebattr()).orElse("");
        aloneReport.setTitle(title);
        String webAttrs = webattr.trim();
        String[] webAttr = webAttrs.split(",");
        if (webAttr.length > 5) {
            return ResultVOUtil.error(ResultEnum.ALONEREPORT_WEBATTR_ERROR);
        }
        for (int i = 0; i < webAttr.length; i++) {
            for (int j = webAttr.length - 1; j > i; j--) {
                if (webAttr[i].equals(webAttr[j])) {
                    return ResultVOUtil.error(ResultEnum.ALONEREPORT_WEBATTR_REPEAT_ERROR);
                }
            }
        }
        for (int i = 0; i < webAttr.length; i++) {
            if (webAttr[i] == null || webAttr[i].equals(""))
                webAttr[i] = "";
            else if (!isUrl(webAttr[i])) {
                return ResultVOUtil.error(ResultEnum.ALONEREPORT_WEBATTR_FORMAT_ERROR);
            }
        }
        String query = null;
        try {
            query = this.getQuery(
                    webAttrs,
                    title,
                    author
            );
        } catch (UnsupportedEncodingException e1) {
            log.error(e1.getMessage());
        }
        aloneReport.setWebattr(webattr);
        aloneReport.setAuthor(author);
        aloneReport.setQuery(query); // 查询条件
        aloneReport.setUserId(user.getUserId()); // 所属用户
        aloneReport.setSubjectOrganizationId(user.getOrganId() + ""); // 所属组织
        /*
         * 报告地址
         */
        String addr = reportForm.getAddr();
        String[] addrs = Convert.split(addr, ",");
        String Useraddrs = "";
        Pattern email = Pattern.compile(StringUtil.VALIDATE_EMAIL);
        Pattern mobile = Pattern.compile(StringUtil.VALIDATE_MOBILE);
        if (addrs.length > 1) {
//            return ResultVOUtil.error(ResultEnum.ALONEREPORT_WEBATTR_ONE_ERROR);
            return ResultVOUtil.error(ResultEnum.PARAM_ERROR);
        }
        for (String add : addrs) {
            if (!email.matcher(add).matches() && !mobile.matcher(add).matches()) {
                return ResultVOUtil.error(55, "添加失败，报告发送地址：" + addr + " 错误！");
            }
            Useraddrs = addr;
        }
        if (Useraddrs == "") {
//            return ResultVOUtil.error(ResultEnum.REPORT_EMAIL_ERROR);
            return ResultVOUtil.error(ResultEnum.PARAM_ERROR);
        }

        int reportManner = StringUtil.getReportManner(manners);
        if (reportManner > 7 || reportManner < 1) {
//            return ResultVOUtil.error(ResultEnum.ALONEREPORT_MANNER_ERROR);
            return ResultVOUtil.error(ResultEnum.PARAM_ERROR);
        }
        aloneReport.setNeedReport(NeedReportEnum.NEED_REPORT.getCode() + "");
        aloneReport.setReportmanner(reportManner + "");
        aloneReport.setReportaddrs(Useraddrs);
        SimpleDateFormat timeFormat = new SimpleDateFormat(DateUtil.TIME_FORMAT);
        aloneReport.setCreatetime(timeFormat.format(new Date())); // 时间条件
        // 保存关键词
        aloneReportService.insertAloneReport(aloneReport);
        return null;
    }

    /**
     * 判断是否有中文字符
     */
    private boolean isChinesePunctuation(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS
                || ub == Character.UnicodeBlock.VERTICAL_FORMS) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isUrl(String str) {
        String regex = "";
        if (!str.contains(","))
            regex = "([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
        return match(regex, str);
    }

    private static boolean match(String regex, String str) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.matches();
    }

    /**
     * 特殊字符处理
     */
    public static boolean stringFilter(String str) {
        String regEx = "[`_~!@#$%^&*={}':;'\\[\\].<>/?~！@#￥%……&*（）——{}【】'；：”“’。，、？]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }

    /*
     * from jsp
     */
    private String getQuery(
            String webattr,
            String title,
            String author

    ) throws UnsupportedEncodingException {

        JSONObject series = new JSONObject();
        JSONObject text = new JSONObject();
        String dm = webattr;
        System.out.println(dm);
        if (dm.contains("http://")) {
            dm = dm.replace("http://", "");
        }
        dm = dm.replace("/", ",");
        dm = dm.replace("；", ",");
        text.put(Search.DOMAIN, (dm == null || dm.isEmpty()) ? new JSONArray() : dm);
        text.put(Search.TITLE, (title == null || title.isEmpty()) ? new JSONArray() : title);
        text.put(Search.AUTHOR, (author == null || author.isEmpty()) ? new JSONArray() : author);
        series.put(Search.QUERY_TEXT, text);
        String[] MTString = {"微博正文", "一般新闻", "主题帖", "微信正文"};
        JSONObject category = new JSONObject();
        String[] SDString = {"新闻", "博客", "政务", "客户端", "电子报", "贴吧", "视频", "电视", "其它"};
        category.put(Search.LOCATION, (PV == null || PV.length == 0) ? new JSONArray() : PV);
        category.put(Search.EMOTION, (EM == null || EM.length == 0) ? new JSONArray() : EM);
        category.put(Search.MEDIA_TYPE, (MD == null || MD.length == 0) ? SDString : MD);
        category.put(Search.MESSAGE_TYPE, (MT == null || MT.length == 0) ? MTString : MT);
        category.put(Search.CHANNEL_CATEGORY, new String[]{});
        series.put(Search.QUERY_CATEGORY, category);
        System.out.println("获取得到的query " + category);
        return series.toString();
    }


    private String[] PV;
    private String[] MD;
    private String[] EM;
    private String[] MT;


    public JSONObject getJSONParam(HttpServletRequest request) {
        JSONObject jsonParam = null;
        try {
            // 获取输入流
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));

            // 写入数据到Stringbuilder
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = streamReader.readLine()) != null) {
                sb.append(line);
            }
            if (StringUtils.isEmpty(sb.toString())) {
                jsonParam = new JSONObject();
            } else
                jsonParam = JSONObject.parseObject(sb.toString());
            // 直接将json信息打印出来
            System.out.println(jsonParam.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonParam;
    }
}
